package com.zhang.common.util;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;

/**
 * LogicUtility
 *
 * @author zhangxin
 * @date 2021/6/20
 */
public final class LogicUtility {
    private static NumberFormat nf;

    public LogicUtility() {
    }

    /**
     * 验证String对象是否是数字
     * Int，double
     * @param strValue
     * @return boolean
     */
    public static boolean isNumber(String strValue) {
        if (strValue != null && strValue.trim().length() != 0) {
            try {
                Integer.parseInt(strValue);
            } catch (Exception var3) {
                return false;
            }

            try {
                Double.parseDouble(strValue);
                return true;
            } catch (Exception var2) {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * String 转 int
     * nDefaultValue 为默认值
     * @param strValue,nDefaultValue
     * @return int
     */
    public static int parseInt(String strValue, int nDefaultValue) {
        return (int)parseDouble(strValue, (double)nDefaultValue);
    }

    public static long parseLong(String strValue, long lDefaultValue) {
        try {
            lDefaultValue = Long.parseLong(strValue);
        } catch (Exception var4) {
        }

        return lDefaultValue;
    }

    /**
     * String 转 Double，dblDefaultValue 为默认值
     * @param strValue,dblDefaultValue
     * @return double
     */
    public static double parseDouble(String strValue, double dblDefaultValue) {
        try {
            dblDefaultValue = Double.parseDouble(strValue);
        } catch (Exception var4) {
        }

        return dblDefaultValue;
    }

    /**
     * String 转成 Color(RGB), 默认 defaultColor
     * @param strRgb,defaultColor
     * @return java.awt.Color
     */
    public static Color parseColor(String strRgb, Color defaultColor) {
        if (strRgb != null && strRgb.length() == 7) {
            strRgb = strRgb.substring(1);
            int rgb = -1;

            try {
                rgb = Integer.parseInt(strRgb, 16);
            } catch (NumberFormatException var4) {
            }

            return rgb < 0 ? defaultColor : new Color(rgb);
        } else {
            return defaultColor;
        }
    }

    /**
     * 当前时间变成String
     * 例：2021-05-28 20:45:18
     * @param
     * @return java.lang.String
     */
    public static String getTimeAsString() {
        return getTimeAsString(new Date());
    }

    /**
     * 时间变成String
     * 例：2021-05-28 20:45:18
     * @param
     * @return java.lang.String
     */
    public static String getTimeAsString(Date date) {
        if (date == null) {
            return "";
        } else {
            Calendar objDate = Calendar.getInstance();
            if (date != null) {
                objDate.setTime(date);
            }

            String strDate = objDate.get(1) + "-" + to2Digits(objDate.get(2) + 1) + "-" + to2Digits(objDate.get(5)) + " " + to2Digits(objDate.get(11)) + ":" + to2Digits(objDate.get(12)) + ":" + to2Digits(objDate.get(13));
            objDate = null;
            return strDate;
        }
    }

    /**
     * 数字变成2位数字
     * @param n
     * @return java.lang.String
     */
    private static String to2Digits(int n) {
        return n < 10 ? "0" + n : String.valueOf(n);
    }

    /**
     * 将 yyyy-mm-dd or yyyy/dd/mm 格式的 String 变成 TimeInMillis
     * @param strTime
     * @return long
     */
    public static long getTimeInMillis(String strTime) {
        long lTime = 0L;

        try {
            strTime = strTime.trim();
            if (strTime.indexOf(" ") > 0) {
                throw new Exception("Time format must be yyyy-mm-dd or yyyy/dd/mm");
            }

            String str = "-";
            int nIndex = strTime.indexOf(str);
            if (nIndex < 0) {
                str = "/";
                nIndex = strTime.indexOf(str);
            }

            int nYear = Integer.parseInt(strTime.substring(0, nIndex));
            strTime = strTime.substring(nIndex + 1);
            nIndex = strTime.indexOf(str);
            int nMonth = Integer.parseInt(strTime.substring(0, nIndex));
            --nMonth;
            if (nMonth < 0) {
                --nYear;
                nMonth = 11;
            }

            int nDay = Integer.parseInt(strTime.substring(nIndex + 1));
            Calendar objDate = Calendar.getInstance();
            objDate.clear();
            objDate.set(nYear, nMonth, nDay);
            lTime = objDate.getTime().getTime();
            objDate = null;
        } catch (Exception var9) {
        }

        return lTime;
    }

    /**
     * 获得当前日期字符串
     * @param
     * @return java.lang.String
     */
    public static String getDateAsString() {
        return getDateAsString(new Date());
    }

    /**
     * 获得日期字符串
     * @param date
     * @return java.lang.String
     */
    public static String getDateAsString(Date date) {
        if (date == null) {
            return "";
        } else {
            Calendar objDate = Calendar.getInstance();
            if (date != null) {
                objDate.setTime(date);
            }

            String strDate = objDate.get(1) + "-" + to2Digits(objDate.get(2) + 1) + "-" + to2Digits(objDate.get(5));
            objDate = null;
            return strDate;
        }
    }

    /**
     * 获得日期字符串
     * 202106
     * @param date
     * @return java.lang.String
     */
    public static String getYearMonth(Date date) {
        Calendar objDate = Calendar.getInstance();
        objDate.setTime(date);
        String strDate = objDate.get(1) + to2Digits(objDate.get(2) + 1);
        return strDate;
    }

    /**
     * 将 String 转 Date
     * @param str
     * @return java.util.Date
     */
    public static Date parseDate(String str) {
        if (str == null) {
            return null;
        } else {
            str = str.trim();
            if (str.length() == 0) {
                return null;
            } else {
                str = str.replace('/', '-');
                str = str.replace('\\', '-');
                String[] sa = str.split("\\s+");
                if (sa != null && sa.length != 0) {
                    String s1 = null;
                    String s2 = null;
                    if (sa.length == 1) {
                        if (sa[0].indexOf(":") > 0) {
                            s2 = sa[0];
                        } else {
                            s1 = sa[0];
                        }
                    }

                    if (sa.length >= 2) {
                        for(int i = 0; sa != null && i < 2 && i < sa.length; ++i) {
                            if (sa[i].indexOf(":") <= 0 && s1 == null) {
                                s1 = sa[i];
                            } else {
                                s2 = sa[i];
                            }
                        }
                    }

                    if (s1 == null) {
                        s1 = "1900-01-01";
                    }

                    if (s2 == null) {
                        s2 = "00:00:00";
                    }

                    int[] ymd = getYmd(s1);
                    int[] hms = getHms(s2);
                    Calendar cal = Calendar.getInstance();
                    cal.set(ymd[0], ymd[1] - 1, ymd[2], hms[0], hms[1], hms[2]);
                    return cal.getTime();
                } else {
                    return null;
                }
            }
        }
    }

    /**
     * Arrays.toString(getHms("20:23")) --> [20, 23, 0]
     * @param s2
     * @return int[]
     */
    private static int[] getHms(String s2) {
        int[] hms = new int[]{0, 0, 0};
        int nEnd = s2.indexOf(":");
        if (nEnd < 0) {
            hms[0] = parseInt(s2, hms[0]);
            return hms;
        } else {
            int nStart = 0;
            hms[0] = parseInt(s2.substring(nStart, nEnd), hms[0]);
            nStart = nEnd + 1;
            if (nStart >= s2.length()) {
                return hms;
            } else {
                nEnd = s2.indexOf(":", nStart);
                if (nEnd < 0) {
                    hms[1] = parseInt(s2.substring(nStart), hms[1]);
                    nEnd = s2.length();
                } else {
                    hms[1] = parseInt(s2.substring(nStart, nEnd), hms[1]);
                }

                nStart = nEnd + 1;
                if (nStart >= s2.length()) {
                    return hms;
                } else {
                    hms[2] = parseInt(s2.substring(nStart), hms[2]);
                    return hms;
                }
            }
        }
    }

    /**
     * Arrays.toString(getYmd("1998-12")) --> [1998, 12, 1]
     * @param s1
     * @return int[]
     */
    private static int[] getYmd(String s1) {
        int[] ymd = new int[]{1900, 1, 1};
        int nEnd = s1.indexOf("-");
        if (nEnd < 0) {
            ymd[0] = parseInt(s1, ymd[0]);
            return ymd;
        } else {
            int nStart = 0;
            ymd[0] = parseInt(s1.substring(nStart, nEnd), ymd[0]);
            nStart = nEnd + 1;
            if (nStart >= s1.length()) {
                return ymd;
            } else {
                nEnd = s1.indexOf("-", nStart);
                if (nEnd < 0) {
                    ymd[1] = parseInt(s1.substring(nStart), ymd[1]);
                    nEnd = s1.length();
                } else {
                    ymd[1] = parseInt(s1.substring(nStart, nEnd), ymd[1]);
                }

                nStart = nEnd + 1;
                if (nStart >= s1.length()) {
                    return ymd;
                } else {
                    ymd[2] = parseInt(s1.substring(nStart), ymd[2]);
                    return ymd;
                }
            }
        }
    }

    /**
     * 判断日期是否为同一天
     * @param dateA,dateB
     * @return boolean
     */
    public static boolean isSameDay(Date dateA, Date dateB) {
        if (dateA != null && dateB != null) {
            Calendar objDateA = Calendar.getInstance();
            objDateA.setTime(dateA);
            Calendar objDateB = Calendar.getInstance();
            objDateB.setTime(dateB);
            if (objDateA.get(1) != objDateB.get(1)) {
                return false;
            } else if (objDateA.get(2) != objDateB.get(2)) {
                return false;
            } else {
                return objDateA.get(5) == objDateB.get(5);
            }
        } else {
            return false;
        }
    }

    public static String getDataString(String strValue) {
        String dbName = "";
        return getDataString(strValue, dbName);
    }

    /**
     * 将数据库日期字符串转换成默认String
     * @param strValue,dbName
     * @return java.lang.String
     */
    public static String getDataString(String strValue, String dbName) {
        StringBuffer stbResult = new StringBuffer("");
        if (strValue != null && strValue.length() > 0) {
            for(int i = 0; i < strValue.length(); ++i) {
                if (strValue.charAt(i) == '\'') {
                    stbResult.append("''");
                } else if (strValue.charAt(i) == '\\' && dbName.equalsIgnoreCase("MySQL")) {
                    stbResult.append("\\\\");
                } else if (strValue.charAt(i) == '&' && dbName.equalsIgnoreCase("Oracle")) {
                    stbResult.append("'||'&'||'");
                } else {
                    stbResult.append(strValue.charAt(i));
                }
            }

            return stbResult.toString();
        } else {
            return "";
        }
    }

    /**
     * duplicateString("qwe ", 5) --> qwe qwe qwe qwe qwe
     * @param strValue,nUnit
     * @return java.lang.String
     */
    public static String duplicateString(String strValue, int nUnit) {
        StringBuffer sb = new StringBuffer("");

        for(int i = 0; i < nUnit; ++i) {
            sb.append(strValue);
        }

        return sb.toString();
    }

    public static String[] splitString(String strValue, String strDelim) {
        if (strValue != null && strDelim != null) {
            StringTokenizer st = new StringTokenizer(strValue, strDelim);
            String[] arrResult = new String[st.countTokens()];

            for(int i = 0; i < arrResult.length; ++i) {
                arrResult[i] = st.nextToken();
            }

            return arrResult;
        } else {
            return null;
        }
    }

    public static String formatNumber(double dbValue, int nFraction) {
        nf.setMaximumFractionDigits(nFraction);
        return nf.format(dbValue);
    }

    public static String formatNumber(String strValue, int nFraction) {
        return formatNumber(parseDouble(strValue, 0.0D), nFraction);
    }

    /**
     * 转变 String 中的特殊字符
     * '"'  &quot;
     * '&'  &amp;
     * '<'  &lt;
     * '>'  &gt;
     * '\\' \\
     * @param strValue
     * @return java.lang.String
     */
    public static String getQuotedString(String strValue) {
        StringBuffer stbResult = new StringBuffer("");
        if (strValue != null && strValue.length() > 0) {
            for(int i = 0; i < strValue.length(); ++i) {
                switch(strValue.charAt(i)) {
                    case '"':
                        stbResult.append("&quot;");
                        break;
                    case '&':
                        stbResult.append("&amp;");
                        break;
                    case '<':
                        stbResult.append("&lt;");
                        break;
                    case '>':
                        stbResult.append("&gt;");
                        break;
                    case '\\':
                        stbResult.append("\\\\");
                        break;
                    default:
                        stbResult.append(strValue.charAt(i));
                }
            }

            return stbResult.toString();
        } else {
            return "";
        }
    }

    /**
     * 将String特殊字符转成HTML格式
     * @param strValue
     * @return java.lang.String
     */
    public static String getHTMLString(String strValue) {
        StringBuffer stbResult = new StringBuffer("");
        char cLast = ' ';

        for(int i = 0; strValue != null && i < strValue.length(); ++i) {
            switch(strValue.charAt(i)) {
                case '\t':
                    stbResult.append("&nbsp;&nbsp;&nbsp;&nbsp;");
                    break;
                case '\n':
                    if (cLast != '\r') {
                        stbResult.append("<br>");
                    }
                    break;
                case '\r':
                    stbResult.append("<br/>");
                    break;
                case ' ':
                    if (cLast == ' ') {
                        stbResult.append("&nbsp;");
                    } else {
                        stbResult.append(" ");
                    }
                    break;
                case '"':
                    stbResult.append("&quot;");
                    break;
                case '&':
                    stbResult.append("&amp;");
                    break;
                case '<':
                    stbResult.append("&lt;");
                    break;
                case '>':
                    stbResult.append("&gt;");
                    break;
                default:
                    stbResult.append(strValue.charAt(i));
            }

            cLast = strValue.charAt(i);
        }

        return stbResult.toString();
    }

    public static String changeHTMLLineSpace(String strValue) {
        StringBuffer stbResult = new StringBuffer("");
        char cLast = ' ';
        if (strValue != null && strValue.length() > 0) {
            for(int i = 0; i < strValue.length(); ++i) {
                switch(strValue.charAt(i)) {
                    case '\t':
                        stbResult.append("&nbsp;&nbsp;&nbsp;&nbsp;");
                        break;
                    case '\n':
                        if (cLast != '\r' && cLast != '>') {
                            stbResult.append("<br/>");
                        }
                        break;
                    case '\r':
                        if (cLast != '>') {
                            stbResult.append("<br/>");
                        }
                        break;
                    case ' ':
                        if (cLast == ' ') {
                            stbResult.append("&nbsp;");
                        } else {
                            stbResult.append(" ");
                        }
                        break;
                    default:
                        stbResult.append(strValue.charAt(i));
                }

                cLast = strValue.charAt(i);
            }
        } else {
            stbResult.append("&nbsp;");
        }

        return stbResult.toString();
    }

    /**
     * 将 String 转成 UTF-8 格式
     * @param strValue
     * @return java.lang.String
     */
    public static String getCNString(String strValue) {
        if (strValue == null) {
            return null;
        } else {
            try {
                byte[] temp = strValue.getBytes("ISO-8859-1");
                return new String(temp, "UTF-8");
            } catch (Exception var2) {
                var2.printStackTrace();
                return null;
            }
        }
    }

    public static byte[] readInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = null;
        Object var2 = null;

        try {
            baos = new ByteArrayOutputStream();
            byte[] buff = new byte[512];
            boolean var4 = false;

            int nLen;
            while((nLen = is.read(buff)) > 0) {
                baos.write(buff, 0, nLen);
            }

            byte[] result = baos.toByteArray();
            return result;
        } catch (IOException var12) {
            throw var12;
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception var11) {
            }

        }
    }

    public static String getOrSQL(String fieldName, Object[] ids) {
        if (ids != null && ids.length != 0) {
            StringBuffer sb = new StringBuffer();

            for(int i = 0; i < ids.length; ++i) {
                Object obj = ids[i];
                if (obj != null) {
                    if (sb.length() > 0) {
                        sb.append(" or ");
                    }

                    sb.append(fieldName).append(" = ");
                    if (obj instanceof String) {
                        sb.append("'").append(obj).append("'");
                    } else {
                        sb.append(obj);
                    }
                }
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    /**
     * getSegmentString("asdasd",2) -> as...
     * getSegmentString("asdasd",8) -> asdasd
     * 获得字符串片段
     * @param strValue,nMaxLen
     * @return java.lang.String
     */
    public static String getSegmentString(String strValue, int nMaxLen) {
        if (strValue != null && nMaxLen > 0) {
            StringBuffer sb = new StringBuffer();
            int nLen = strValue.length();
            int i = 0;

            for(int hasGet = 0; i < nLen; ++i) {
                char c = strValue.charAt(i);
                if (c > 255) {
                    hasGet += 2;
                } else {
                    ++hasGet;
                }

                if (hasGet > nMaxLen) {
                    break;
                }

                sb.append(c);
            }

            if (i < nLen) {
                sb.append("...");
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    public static InputStream getResourceAsStream(String resource) throws IOException {
        String stripped = resource.startsWith("/") ? resource.substring(1) : resource;
        InputStream stream = null;
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader != null) {
            stream = classLoader.getResourceAsStream(stripped);
        }

        if (stream == null) {
            stream = LogicUtility.class.getResourceAsStream(resource);
        }

        if (stream == null) {
            stream = LogicUtility.class.getClassLoader().getResourceAsStream(stripped);
        }

        if (stream == null) {
            throw new IOException(resource + " not found");
        } else {
            return stream;
        }
    }

    /**
     * 文件复制
     * @param src,dest
     * @return boolean
     */
    public static boolean moveFile(File src, File dest) {
        if (src != null && dest != null) {
            File dir = dest.getParentFile();
            if (dir != null && !dir.exists()) {
                dir.mkdirs();
            }

            byte[] buff = new byte[512];
            InputStream is = null;
            FileOutputStream os = null;

            try {
                is = new FileInputStream(src);
                os = new FileOutputStream(dest, false);
                int loopTimes = 0;

                int len;
                while((len = is.read(buff)) > 0) {
                    os.write(buff, 0, len);
                    ++loopTimes;
                    if (loopTimes > 0 && loopTimes / 1024 == 0) {
                        os.flush();
                    }
                }
            } catch (Exception var20) {
                var20.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Exception var19) {
                }

                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (Exception var18) {
                }

            }

            return src.delete();
        } else {
            return false;
        }
    }

    /**
     * 得到文件名后缀
     * @param fileName
     * @return java.lang.String
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        } else {
            int nIndex = fileName.lastIndexOf(".");
            return nIndex >= 0 ? fileName.substring(nIndex + 1) : "";
        }
    }

    /**
     * 短了补0，长了不变
     * toDigitString(19, 5) -> 00019
     * @param n,len
     * @return java.lang.String
     */
    public static String toDigitString(int n, int len) {
        String s;
        for(s = String.valueOf(n); s.length() < len; s = "0" + s) {
        }

        return s;
    }

    /**
     * 短了补0，长了不变
     * toDigitString(19, 5) -> 00019
     * @param n,len
     * @return java.lang.String
     */
    public static String toDigitString(long n, int len) {
        String s;
        for(s = String.valueOf(n); s.length() < len; s = "0" + s) {
        }

        return s;
    }

    /**
     * 得到String的Ascii
     * @param v
     * @return java.lang.String
     */
    public static String toAsciiString(String v) {
        if (v != null && v.length() != 0) {
            StringBuffer sb = new StringBuffer();
            char[] cs = v.toCharArray();

            for(int i = 0; i < cs.length; ++i) {
                if (cs[i] < 128) {
                    sb.append(cs[i]);
                } else {
                    String temp;
                    for(temp = Integer.toHexString(cs[i] & -1); temp.length() < 4; temp = "0" + temp) {
                    }

                    sb.append("\\u").append(temp);
                }
            }

            return sb.toString();
        } else {
            return v;
        }
    }

    /**
     * 获得 length 长度的随机数字
     * @param length
     * @return java.lang.String
     */
    public static String getRandomNumber(int length) {
        String serial = "0123456789";
        Random random = new Random();
        int n = serial.length();
        StringBuffer code = new StringBuffer();

        for(int i = 0; i < length; ++i) {
            code.append(serial.charAt(random.nextInt(n)));
        }

        return code.toString();
    }

    /**
     * String logId = LogicUtility.getUUID();
     * @param
     * @return java.lang.String
     */
    public static synchronized String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获得 length 长度的随机字符串
     * @param length
     * @return java.lang.String
     */
    public static String getRandomString(int length) {
        String codeSerial = "1234567890abcdefghkmnpqrstwxyABCDEFGHKLMNPQRSTWXY";
        Random random = new Random();
        int n = codeSerial.length();
        StringBuffer code = new StringBuffer();

        for(int i = 0; i < length; ++i) {
            code.append(codeSerial.charAt(random.nextInt(n)));
        }

        return code.toString();
    }


    static {
        nf = NumberFormat.getNumberInstance(Locale.CHINA);
    }

    public static void main(String[] args) {
        System.out.println(getSegmentString("asdasd",2));
    }
}

